from django.http import JsonResponse, HttpResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Recruit, Enterprise, City
from .serializer import RecommendSerializer, EnterpriseSerializer, CityHostListSerializer, \
    RecruitsDeatilsSerializer, EnterpriseDeatilsSerializer


class RecommendListView(APIView):

    # GET / recruits / search / recommend /
    def get(self, request):
        '''
        1.获取所有招聘信息,按id降序取前4个
        2.通过json返回
        '''

        queryset = Recruit.objects.all().order_by('-id')[:4]
        serializer = RecommendSerializer(instance=queryset, many=True)
        return Response(serializer.data)


# 获取最新职位信息
class LatestListView(APIView):
    # recruits/search/latest/
    def get(self, request):
        '''
        1.获取最新职位信息,按createtime降序取前4个
        2.通过json返回
        '''
        queryset = Recruit.objects.all().order_by('-createtime')[:4]
        serializer = RecommendSerializer(instance=queryset, many=True)
        return Response(serializer.data)


# 热门企业
class EnterpriseHotListListView(APIView):
    # /enterprise/search/hotlist/
    def get(self, request):

        queryset = Enterprise.objects.all().order_by('-visits')[:4]
        serializer = EnterpriseSerializer(instance=queryset, many=True)
        return Response(serializer.data)


# 热门城市
class CityHostListListView(APIView):
    # city/hotlist/
    def get(self, request):

        queryset = City.objects.filter(ishot=1)
        serializer = CityHostListSerializer(instance=queryset, many=True)
        return Response(serializer.data)


# 职位详情
class RecruitsDetailsListView(APIView):
        # recruits/{id}/
    def get(self, request, pk):
        '''
        1.传参id,根据pk去数据库查询指定的职位数据
        2.获取id对应的职位详情
        3.返回json
        '''
        try:
            recruits = Recruit.objects.get(id=pk)
        except Recruit.DoesNotExist:
            raise JsonResponse({'message':'not found'}, status=404)

        # 创建序列化器
        serializer = RecruitsDeatilsSerializer(recruits)
        # 返回数据
        return JsonResponse(serializer.data)


# 增加某个职位的访问量
class JobVisitListView(APIView):
    # recruits/{id}/visit/
    def put(self, request, pk):
        '''
        form表单格式,不是json
        1.在数据库访问一次pk对象,浏览量加1
        2.返回{"message":"更新成功","success":true}
        '''

        recruits = Recruit.objects.get(id=pk)
        recruits.visits += 1
        recruits.save()
        return HttpResponse({"message":"更新成功","success":"true"})


# 增加企业的访问量
class EnterpriseVisitListView(APIView):
    # enterprise/{id}/visit/

    def put(self, request, pk):
        '''
        form表单格式,不是json
        1.在数据库访问一次pk对象,浏览量加1
        2.返回{"message":"更新成功","success":true}
        '''

        enterprise = Enterprise.objects.get(id=pk)
        enterprise.visits += 1
        enterprise.save()
        return HttpResponse({"message":"更新成功","success":"true"})


# 企业详情
class EnterpriseDetailListView(APIView):
    # enterprise/{id}/
    def get(self, request, pk):
        '''
        1.获取企业详情
        2.返回json
        '''
        try:
            enterprise = Enterprise.objects.get(id=pk)
        except Enterprise.DoesNotExist:
            raise JsonResponse({'message':'not found'}, status=404)

        serializer = EnterpriseDeatilsSerializer(enterprise)
        return JsonResponse(serializer.data)


# 收藏公司
class EPCollectListView(APIView):
    #  /enterprise/{id}/collect/
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        '''
        1.找到pk对应的公司
        2.找到公司的所有users
        3.判断公司的users中是否有这个当前用户的id
        4.没有,添加
        '''
        enterprise = Enterprise.objects.get(id=pk)
        enterprise.users.add(request.user)
        enterprise.save()
        return Response({"success":"true","message":"收藏成功"})


# 取消收藏公司
class EPCancelCollectListView(APIView):
    # /enterprise/3/cancelcollect/
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        enterprise = Enterprise.objects.get(id=pk)
        enterprise.users.remove(request.user)
        enterprise.save()
        return Response({"success": "true", "message": "取消收藏成功"})


# 收藏职位
class JobCollectListView(APIView):
    #  /recruits/{id}/collect/
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        recruit = Recruit.objects.get(id=pk)
        recruit.users.add(request.user)
        recruit.save()
        return Response({"success": "true", "message": "收藏成功"})


# 取消收藏职位
class JobCancelCollectListView(APIView):
    #  recruits/4/cancelcollect/
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        recruit = Recruit.objects.get(id=pk)
        recruit.users.remove(request.user)
        recruit.save()

        return Response({"success": "true", "message": "取消收藏成功"})


# 搜索职位
class SearchKeywordListView(APIView):
    # recruits/search/city/keyword/

    def post(self, request):
        '''
        1.接收参数
        2.按照创建时间展示状态为1的所有职位
        3.创建一个空列表
        4.将传递进来的参数查询到的数据加入到列表中
        5.列表为序列化器的data
        6.返回json
        '''
        name = request.data['cityname']
        keyword = request.data['keyword']

        req_data = []
        jobs = Recruit.objects.filter(state='1').order_by('-createtime')

        # name和keyword都没有传
        if not name and not keyword:
            req_data = jobs

        # 只传name
        if name and not keyword:
            for job in jobs:
                if job.city == name:
                    req_data.append(job)

        # 只传keyword
        if keyword and not name:
            for job in jobs:
                if job.jobname.lower().find(keyword.lower()) != -1:
                    req_data.append(job)

        # 两个都传了
        if keyword and name:
            for job in jobs:
                if job.city == name and job.jobname.lower().find(keyword.lower()) != -1:
                    req_data.append(job)

        serializer = RecommendSerializer(req_data, many=True)

        return Response(serializer.data)


# # 索引视图
# class SearchKeywordViewSet(HaystackViewSet):
#     """
#     Recruit搜索
#     """
#     index_models = [Recruit]
#
#     serializer_class = RecruitIndexSerializer